﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient
Imports Microsoft.Samples.WindowsPhoneCloud.Phone.Models
Imports System.Windows.Threading
Imports System.Globalization
Imports System.ComponentModel

Namespace ViewModel

    Public Class SampleDataDetailsPageViewModel
        Inherits BaseViewModel
        Private ReadOnly context As ITableServiceContext
        Private ReadOnly dispatcher As Dispatcher

        Private sampleDataValue As SampleData
        Private messageValue As String
        Private isSavingValue As Boolean = False

        Public Sub New()
            Me.New(App.CloudClientFactory.ResolveTablesServiceContext("SampleData"), Deployment.Current.Dispatcher)
        End Sub

        Public Sub New(ByVal context As ITableServiceContext, ByVal dispatcher As Dispatcher)
            Me.context = context
            Me.dispatcher = dispatcher
        End Sub

        Public Event SaveChangesSuccess As EventHandler

        Public Property SampleData() As SampleData
            Get
                Return Me.sampleDataValue
            End Get

            Set(ByVal value As SampleData)
                If Me.sampleDataValue IsNot value Then
                    Me.sampleDataValue = value
                    Me.NotifyPropertyChanged("SampleData")
                End If
            End Set
        End Property

        Public Property Message() As String
            Get
                Return Me.messageValue
            End Get

            Set(ByVal value As String)
                If Me.messageValue <> value Then
                    Me.messageValue = value
                    Me.NotifyPropertyChanged("Message")
                End If
            End Set
        End Property

        Public Property IsSaving() As Boolean
            Get
                Return Me.isSavingValue
            End Get

            Set(ByVal value As Boolean)
                If Me.isSavingValue <> value Then
                    Me.isSavingValue = value
                    Me.NotifyPropertyChanged("IsSaving")
                End If
            End Set
        End Property

        Public Sub SetSampleDataModel(Optional ByVal sampleData As SampleData = Nothing)
            If sampleData Is Nothing Then
				Me.SampleData = New SampleData()
                Try
                    Me.context.AddObject("SampleData", Me.SampleData)
                Catch exception As Exception
                    Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                    Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
                End Try
            Else
                Me.SampleData = sampleData
                AddHandler Me.SampleData.PropertyChanged, AddressOf OnUpdateSampleData
            End If
        End Sub

        Public Sub DeleteSampleData()
            Me.Message = "Deleting..."
            Me.IsSaving = True

            RemoveHandler Me.SampleData.PropertyChanged, AddressOf OnUpdateSampleData

            Try
                Me.context.DeleteObject(Me.SampleData)
                Me.context.BeginSaveChanges(AddressOf Me.OnBeginSaveChanges, Nothing)
            Catch exception As Exception
                Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                Me.IsSaving = False
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
            End Try
        End Sub

        Public Sub SaveSampleData()
            Me.Message = "Saving..."
            Me.IsSaving = True

            Try
                Me.context.BeginSaveChanges(AddressOf Me.OnBeginSaveChanges, Nothing)
            Catch exception As Exception
                Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                Me.IsSaving = False
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
            End Try
        End Sub

        Private Sub OnUpdateSampleData(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
            RemoveHandler Me.SampleData.PropertyChanged, AddressOf OnUpdateSampleData

            Try
                Me.context.UpdateObject(Me.SampleData)
            Catch exception As Exception
                Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
            End Try
        End Sub

        Private Sub OnBeginSaveChanges(ByVal asyncResult As IAsyncResult)
            Me.dispatcher.BeginInvoke(Sub()
                                          Try
                                              Me.context.EndSaveChanges(asyncResult)
                                              Me.Message = "Changes saved successfully."
                                              Me.IsSaving = False
                                              Me.RaiseSaveChangesSuccess()
                                          Catch exception As Exception
                                              Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", StorageClientExceptionParser.ParseDataServiceException(exception).Message)
                                              Me.IsSaving = False
                                          End Try
                                      End Sub)
        End Sub

    Private Sub RaiseSaveChangesSuccess()
        RaiseEvent SaveChangesSuccess(Me, EventArgs.Empty)
    End Sub
    End Class
End Namespace